package com.njzxw.fs.serversys.server;

import com.njzxw.fs.commonutil.util.StringHelper;
import com.njzxw.fs.commonutil.web.BaseServer;
import com.njzxw.fs.commonutil.web.ReturnMap;
import com.njzxw.fs.serversys.bean.WeiXinBean;
import com.njzxw.fs.serversys.feign.WeixinClent;
import com.njzxw.fs.serversys.repository.UserReq;
import net.sf.json.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
public class WeiXinServer extends BaseServer{

    @Autowired
    private WeixinClent weixinClent;

    @Autowired
    private UserReq userReq;

    public ReturnMap weixinClent(WeiXinBean weiXinBean) {
        String result = weixinClent.code2Session(common.getSystem("APPID"),common.getSystem("APP_SECRET"),weiXinBean.getCode(),"authorization_code");
        logger.debug("获取微信小程序信息："+result);
        JSONObject json = JSONObject.fromObject(result);
        if(json.containsKey("openid")){
            String openid = json.getString("openid");
            String session_key = json.getString("session_key");
            String uinionid = json.containsKey("uinionid")?json.getString("uinionid"):null;
            //记录opernId

            weiXinBean.setWexi_id(openid);
            weiXinBean.setUuid(uinionid);
            if(userReq.checkWxOperIdUser(weiXinBean) <= 0){
                if(userReq.insertWxUser(weiXinBean) <= 0 ){
                    return returnMap.getErrorReturnMap("更新错误，请重新获取");
                }
            }else{
                if(userReq.updateWxUser(weiXinBean) <= 0){
                    return returnMap.getErrorReturnMap("更新错误，请重新获取");
                }
                weiXinBean.setId(String.valueOf(userReq.selectUserId(weiXinBean)));
            }

            String token = UUID.randomUUID().toString();

            Map<String,Object> map = new HashMap<>();
            map.put("id",weiXinBean.getId());
            map.put("oper_id",openid);
            logger.info("微信用户信息："+map);
            //校验是否已经绑定，如果没有绑定手机号给与提示
            Integer exc = userReq.checkWxMobile(weiXinBean);
            if(exc < 0){
                return returnMap.getErrorReturnMap("更新错误，请重新获取");
            }else if(exc == 1){
                returnMap.setReturnMap("isBdMobile","1");
            }else{
                returnMap.setReturnMap("isBdMobile","0");
            }

            redisUtil.setKey(token, JSONObject.fromObject(map).toString(),Long.valueOf(common.getSystem("LOGIN.OUT.TIME")), TimeUnit.MINUTES);

            returnMap.setReturnMap("openid",openid);
            returnMap.setReturnMap("token",token);
            return returnMap.getSucceeReturnMap();
        }else{
            return returnMap.getErrorReturnMap("获取信息出现异常，请重新获取");
        }
    }

    public ReturnMap reg(WeiXinBean weiXinBean) {

        String codestr = redisUtil.getValue(weiXinBean.getImgCodeUuid(),String.class);
        if(StringUtils.isBlank(codestr)){
            return returnMap.getErrorReturnMap("验证码已失效，请重新点击验证码刷新");
        }

        if(!codestr.equals(weiXinBean.getCode())){
            return returnMap.getErrorReturnMap("验证码填写不正确");
        }

        Map<String,Object> dataMap = weiXinBean.getData();

        Iterator<String> it = dataMap.keySet().iterator();

        String tokenstr = redisUtil.getValue(weiXinBean.getToken(),String.class);
        if(StringUtils.isBlank(tokenstr)){
            return returnMap.getErrorReturnMap("拉取信息失败，请重新打开小程序再试哦");
        }
        String oper_id = JSONObject.fromObject(tokenstr).getString("oper_id");

        String sql = "update t_user_info a set ";

        while(it.hasNext()){
            String name = it.next();
            sql += " a.`"+name+"` = '"+ StringHelper.get(dataMap,name)+"',";
        }
        sql = sql.substring(0,sql.length()-1);
        sql += " where a.wexi_id = '"+oper_id+"'";

        if(userReq.update(sql) <= 0){
            return returnMap.getErrorReturnMap("绑定失败，请重新操作");
        }

        return returnMap.getSucceeReturnMap();
    }

    public void getCode(HttpServletRequest request, HttpServletResponse response) {
        try {
            String width = req.getAjaxValue(request, "w");
            String height = req.getAjaxValue(request, "h");
            String codeLength = req.getAjaxValue(request, "l");
            String uuid = req.getAjaxValue(request, "UUID");
            String type = req.getAjaxValue(request, "type");//1登录
            if (!validator.isInteger(width)) {
                width = "76";
            }
            if (!validator.isInteger(height)) {
                height = "38";
            }
            if (!validator.isInteger(codeLength)) {
                codeLength = "4";
            }

            String code = verifyCodeUtils.generateVerifyCode(Integer.valueOf(codeLength));
            logger.debug("获取绑定验证码12："+uuid+"==" + code + "--" + width + "---" + height+"---"+redisUtil.getValue(uuid,String.class));

            redisUtil.setKey(uuid,code,5L, TimeUnit.MINUTES);

            logger.debug(uuid+"coderedis:"+redisUtil.getValue(uuid,String.class));

            verifyCodeUtils.outputImage(Integer.valueOf(width), Integer.valueOf(height), response, code);

        } catch (IOException e) {
            logger.error("验证码生成出错：", e);
        }
    }

    public ReturnMap getInfo(HttpServletRequest request, HttpServletResponse response,WeiXinBean weiXinBean) {
        Map<String,Object> map = userReq.getWeiXinInfo(weiXinBean);
        returnMap.setDataMaps(map);
        return returnMap.getSucceeReturnMap();
    }

    public ReturnMap saveInfo(HttpServletRequest request, HttpServletResponse response, WeiXinBean weiXinBean) {

        Map<String,Object> dataMap = weiXinBean.getData();

        Iterator<String> it = dataMap.keySet().iterator();

        String tokenstr = redisUtil.getValue(weiXinBean.getToken(),String.class);
        if(StringUtils.isBlank(tokenstr)){
            return returnMap.getErrorReturnMap("拉取信息失败，请重新打开小程序再试哦");
        }
        String oper_id = JSONObject.fromObject(tokenstr).getString("oper_id");

        String sql = "update t_user_info a set ";

        while(it.hasNext()){
            String name = it.next();
            sql += " a.`"+name+"` = '"+ StringHelper.get(dataMap,name)+"',";
        }
        sql = sql.substring(0,sql.length()-1);
        sql += " where a.wexi_id = '"+oper_id+"'";

        if(userReq.update(sql) <= 0){
            return returnMap.getErrorReturnMap("保存信息失败，请重新操作");
        }

        return returnMap.getSucceeReturnMap();

    }
}
